package com.itlong.cloud.property.service.impl;

import com.itlong.cloud.POJO.PO.ColectionRatePo;
import com.itlong.cloud.POJO.PO.TimeTaskPropertyCostStatisticsPO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.enumerate.DataStatusEnum;
import com.itlong.cloud.property.dao.IPropertyOperatingReportDao;
import com.itlong.cloud.property.service.IPropertyOperatingReportService;
import com.itlong.cloud.utils.data.handler.SqlUtil;
import com.itlong.cloud.utils.date.DateUtil;
import com.itlong.cloud.utils.node.JsonUtil;
import com.itlong.cloud.utils.random.LogicIdUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * <desc>
 *      运营报表业务处理接口实现类
 * </desc>
 *
 * @createDate 2018/08/13
 */
@Service
public class PropertyOperatingReportServiceImpl implements IPropertyOperatingReportService{

    @Autowired
    IPropertyOperatingReportDao iPropertyOperatingReportDao;

    /**
     * <desc>
     *      统计每月的缴费及欠费总额
     * </desc>
     *
     * @author Jiaqi.X
     * @createDate 2018/08/13
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public void statisticsForMonth() throws Exception {
        //获取所有项目
        List<String> projectIds = iPropertyOperatingReportDao.getProjects();
        for(String projectId : projectIds){
            //获取项目下的账单数据最大日期及最小日期
            Map<String,String> timeMap = iPropertyOperatingReportDao.getProjectMaxMonthAndMinMonth(projectId);
            if(timeMap!=null){
                int month = DateUtil.getTwoMonthDifference(timeMap.get("minTime"),timeMap.get("maxTime"));
                String date = timeMap.get("minTime");
                do{
                    //删除当月统计的数据
                    iPropertyOperatingReportDao.deleteForMonth(date,projectId,1);
                    //统计每月已缴费报表数据
                    List<Map<String,Object>> fees = new ArrayList<>();
                    List<Map<String,Object>> payments = iPropertyOperatingReportDao.statisticsPaymentForDay(date, projectId, 1);
                    List<Map<String,Object>> services = iPropertyOperatingReportDao.statisticsServiceFee(date, projectId, 2);
                    if(payments!=null){
                        fees.addAll(payments);
                    }
                    if(services!=null){
                        fees.addAll(services);
                    }
                    if(fees !=null && !fees.isEmpty()) {
                        TimeTaskPropertyCostStatisticsPO po = getPoByDataMap(fees);
                        po.setStatisticsType(2);
                        po.setProjectId(projectId);
                        po.setCostType(1);
                        po.setStatisticsId(LogicIdUtil.bussinessId());
                        po.setStatisticsTime(DateUtil.formatStringToDate(date,"yyyy-MM"));
                        iPropertyOperatingReportDao.save(SqlUtil.durableData(po, PlatformConstants.TABLE_SAVE));
                    }
                    //统计每月未缴费报表数据
                    List<Map<String,Object>> arrearages = new ArrayList<>();
                    List<Map<String,Object>> unpaids = iPropertyOperatingReportDao.statisticsPaymentForDay(date, projectId, 0);
                    List<Map<String,Object>> aservices = iPropertyOperatingReportDao.statisticsServiceFee(date, projectId, 1);
                    if(unpaids!=null){
                        arrearages.addAll(unpaids);
                    }
                    if(aservices!=null){
                        arrearages.addAll(aservices);
                    }
                    if(arrearages !=null && !arrearages.isEmpty()) {
                        TimeTaskPropertyCostStatisticsPO po = getPoByDataMap(arrearages);
                        po.setStatisticsType(2);
                        po.setCostType(2);
                        po.setProjectId(projectId);
                        po.setStatisticsTime(DateUtil.formatStringToDate(date,"yyyy-MM"));
                        po.setStatisticsId(LogicIdUtil.bussinessId());
                        iPropertyOperatingReportDao.save(SqlUtil.durableData(po, PlatformConstants.TABLE_SAVE));
                    }
                    //统计每月应缴报表数据
                    List<Map<String,Object>> paidsList = new ArrayList<>();
                    List<Map<String,Object>> paids = iPropertyOperatingReportDao.statisticsPaymentForDay(date, projectId, 2);
                    List<Map<String,Object>> ervices = iPropertyOperatingReportDao.statisticsServiceFee(date, projectId, 3);
                    if(paids!=null){
                        paidsList.addAll(paids);
                    }
                    if(ervices!=null){
                        paidsList.addAll(ervices);
                    }
                    if(paidsList !=null && !paidsList.isEmpty()) {
                        TimeTaskPropertyCostStatisticsPO po = getPoByDataMap(paidsList);
                        po.setStatisticsType(2);
                        po.setCostType(3);
                        po.setProjectId(projectId);
                        po.setStatisticsTime(DateUtil.formatStringToDate(date,"yyyy-MM"));
                        po.setStatisticsId(LogicIdUtil.bussinessId());
                        iPropertyOperatingReportDao.save(SqlUtil.durableData(po, PlatformConstants.TABLE_SAVE));
                    }
                    //计算月份增加
                    date = DateUtil.fomatDate(DateUtil.addCurrentTimeOfMonth(DateUtil.formatStringToDate(date,"yyyy-MM"),1),"yyyy-MM");
                    month--;
                }while(month >= 0);
            }
        }
    }

    /**
     * <desc>
     *      通过查询到的map数据封装成po
     * </desc>
     *
     * @param payments
     * @return
     * @author Jiaqi.X
     * @createDate 2018/08/13
     */
    private TimeTaskPropertyCostStatisticsPO getPoByDataMap(List<Map<String,Object>> payments){
        TimeTaskPropertyCostStatisticsPO po = new TimeTaskPropertyCostStatisticsPO();
        po.setCreateTime(new Date());
        po.setStatus(DataStatusEnum.NORMAL.getType());
        for(Map<String,Object> payment : payments){
            switch (Integer.valueOf(payment.get("type").toString())){
                case 1:
                    //水费
                    po.setWaterRate(new BigDecimal(payment.get("money").toString()));
                    break;
                case 2:
                    //电费
                    po.setPowerRate(new BigDecimal(payment.get("money").toString()));
                    break;
                case 3:
                    //燃气费
                    po.setGasBill(new BigDecimal(payment.get("money").toString()));
                    break;
                case 4:
                    //物业费
                    po.setPropertyFee(new BigDecimal(payment.get("money").toString()));
                    break;
                case 5:
                    //维修费
                    po.setAttendanceCost(new BigDecimal(payment.get("money").toString()));
                    break;
                case 6:
                    //停车费
                    po.setParkingFee(new BigDecimal(payment.get("money").toString()));
                    break;
            }
        }
        return po;
    }

    /**
     * <desc>
     *      统计每年的缴费及欠费总额
     * </desc>
     *
     * @author Jiaqi.X
     * @createDate 2018/08/13
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public void statisticsForYear() throws Exception {
        //获取所有项目
        List<String> projectIds = iPropertyOperatingReportDao.getProjects();
        for(String projectId : projectIds){
            //获取项目下的账单数据最大年份及最小年份
            Map<String,String> timeMap = iPropertyOperatingReportDao.getProjectMaxYearAndMinYear(projectId);
            if(timeMap!=null) {
                int yearCount = DateUtil.yearsBetween(timeMap.get("minTime"),timeMap.get("maxTime"));
                //获取当前年份
                String year = timeMap.get("minTime");
                do {
                    //删除当年的统计数据,重新统计
                    iPropertyOperatingReportDao.deleteForMonth(year, projectId, 2);
                    //统计当年的缴费数据
                    TimeTaskPropertyCostStatisticsPO yearPaid = iPropertyOperatingReportDao.statisticsPaymentForMonth(year, projectId, 1, 2);
                    if (yearPaid != null) {
                        yearPaid.setStatisticsId(LogicIdUtil.bussinessId());
                        yearPaid.setStatus(DataStatusEnum.NORMAL.getType());
                        yearPaid.setCreateTime(new Date());
                        yearPaid.setStatisticsType(3);
                        yearPaid.setCostType(1);
                        yearPaid.setStatisticsTime(DateUtil.formatStringToDate(year, "yyyy"));
                        yearPaid.setProjectId(projectId);
                        System.out.println(JsonUtil.toJSON(yearPaid));
                        iPropertyOperatingReportDao.save(SqlUtil.durableData(yearPaid, PlatformConstants.TABLE_SAVE));
                    }
                    //年份+1
                    year = DateUtil.fomatDate(DateUtil.getAddYear(DateUtil.formatStringToDate(year,"yyyy"),1),"yyyy");
                    yearCount--;
                }while(yearCount >= 0);
            }
        }
    }

    /**
     * <desc>
     *      统计运营分析物业增值数据
     * </desc>
     *
     * @createDate 2019/06/17
     * @author Jiaqi.X
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public void statisticsAnalyseForMonth() throws Exception {
        //获取所有项目
        List<String> projectIds = iPropertyOperatingReportDao.getStatisticsReportProjects();
        //删除旧数据
        iPropertyOperatingReportDao.deleteAnalyData();
        for(String projectId : projectIds){
            //处理每月数据
            List<Map<String,Object>> list = iPropertyOperatingReportDao.getMonthListByProjectId(projectId);
            for(Map<String,Object> map : list){
                //查询分润费
                String money = iPropertyOperatingReportDao.getShareMoneyByProjectIdAndMonth(map.get("projectId").toString(),map.get("month").toString());
                ColectionRatePo po = new ColectionRatePo();
                po.setColectionRateId(LogicIdUtil.bussinessId());
                po.setPaidMoney(map.get("paidMoney").toString());
                po.setTotalMoney(map.get("dueMoney").toString());
                po.setColectionRate(po.getTotalMoney().equals("0.00") || po.getPaidMoney().equals("0.00") ? "0" : new BigDecimal(po.getPaidMoney()).divide(new BigDecimal(po.getTotalMoney()), 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal("100")).setScale(2, BigDecimal.ROUND_DOWN).toString());
                po.setShareTotal(StringUtils.isNotBlank(money) ? money : "0.00");
                po.setProjectId(map.get("projectId").toString());
                po.setMonth(DateUtil.formatStringToDate(map.get("month").toString(), DateUtil.YYYYMM));
                po.setCreateTime(new Date());
                po.setStatus(DataStatusEnum.NORMAL.getType());
                iPropertyOperatingReportDao.save(SqlUtil.durableData(po,PlatformConstants.TABLE_SAVE));
            }
        }
    }

    public static void main(String[] args) {
        System.out.println( new BigDecimal("3121.40").divide(new BigDecimal("3061.40"), 2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal("100")).toString());
    }

    /**
     * <desc>
     *      获取项目下的报表信息
     * </desc>
     *
     * @param projectId
     * @param startTime
     * @param endTime
     * @return
     * @author Jiaqi.X
     * @createDate 2018/08/13
     */
    @Override
    public Map<String, Object> chargeStatistics(String projectId,String startTime,String endTime) {
        Map<String,Object> result = new HashMap<>();
        String endYear="";
        if(StringUtils.isBlank(startTime) && StringUtils.isBlank(endTime)){
            startTime = DateUtil.fomatDate(new Date(),"yyyy-MM");
        }
        String startYear =StringUtils.isBlank(startTime) ? endTime.substring(0,4): startTime.substring(0,4);
        endYear= StringUtils.isBlank(endTime) ?  startTime.substring(0,4) : endTime.substring(0,4);
        result.put("paymentTotal",iPropertyOperatingReportDao.getDataByMonth(startTime,endTime,1,projectId));
        result.put("arrearageTotal",iPropertyOperatingReportDao.getDataByMonth(startTime,endTime,0,projectId));
        startTime = startYear+"-01";
        endTime = endYear+"-12";
        result.put("yearBill", iPropertyOperatingReportDao.getDataByMonth(startTime, endTime, 1, projectId));
        return result;
    }

}
